import 'package:flutter/material.dart';
import 'package:photo_view/photo_view_gallery.dart';

typedef PageChanged = void Function(int index);

class PhotoPreview extends StatefulWidget {
  final List galleryItems; //图片列表
  final int defaultImage; //默认第几张
  final PageChanged? pageChanged; //切换图片回调
  final Axis direction; //图片查看方向
  final BoxDecoration? decoration; //背景设计

  const PhotoPreview(
      {Key? key,
      required this.galleryItems,
      this.defaultImage = 1,
      this.pageChanged,
      this.direction = Axis.horizontal,
      this.decoration})
      : assert(galleryItems != null),
        super(key: key);

  @override
  _PhotoPreviewState createState() => _PhotoPreviewState();
}

class _PhotoPreviewState extends State<PhotoPreview> {
  late int tempSelect;

  @override
  void initState() {
    // TODO: implement initState
    tempSelect = widget.defaultImage + 1;
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.black,
      child: Stack(
        children: [
          PhotoViewGallery.builder(
              scrollPhysics: const BouncingScrollPhysics(),
              builder: (BuildContext context, int index) {
                return PhotoViewGalleryPageOptions(
                  imageProvider: NetworkImage(widget.galleryItems[index]),
                );
              },
              scrollDirection: widget.direction,
              itemCount: widget.galleryItems.length,
              backgroundDecoration: widget.decoration?? const BoxDecoration(color: Colors.black),
              pageController:
                  PageController(initialPage: widget.defaultImage),
              onPageChanged: (index) => setState(() {
                    tempSelect = index + 1;
                    if (widget.pageChanged != null) {
                      widget.pageChanged!(index);
                    }
                  })),
          Align(
            alignment: Alignment.topCenter,
            child: Text(
              '\n\n\n$tempSelect/${widget.galleryItems.length}',
              style: const TextStyle(color: Colors.white),
            ),
          ),
          Positioned(
            left: 10,
            top: 52,
            width: 48,
            height: 48,
            child: GestureDetector(
              onTap: () {
                Navigator.of(context).pop();
              },
              child: const Icon(
                Icons.close,
                color: Colors.white,
                size: 20,
              ),
            ),
          )
        ],
      ),
    );
  }
}
